package cn.wolfcode.education.web.filter;

import cn.wolfcode.education.domain.Employee;
import cn.wolfcode.education.domain.Menu;
import cn.wolfcode.education.service.IMenuService;
import cn.wolfcode.education.util.JSONResult;
import cn.wolfcode.education.util.MenuUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.PrintWriter;
import java.util.List;

/**
 * 扩展  FormAuthenticationFilter认证器 ,实现直接的结果响应
 */
public class ExtendFormAuthenticationFilter extends FormAuthenticationFilter {
    @Autowired
    private IMenuService menuService;
    public void setMenuService(IMenuService menuService) {
        this.menuService = menuService;
    }


    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response)
            throws Exception {

        //登陆成功之后,过滤出属于当前用户的菜单 ,放入session中 ,前台从session中获取菜单
        //1.获取所有的菜单
        List<Menu> allMenus = menuService.selectAllParent();

        //获取登陆用户
        Employee employee = (Employee) subject.getPrincipal();

        //2.判断如果不是超级管理员
        if(!employee.isAdmin()){
            //2.1获取属于用户的菜单的id的集合
            List<Long> ids = menuService.listIdsByEmployeeId(employee.getId());
            //2.2递归过滤出只属于用户的菜单
            MenuUtil.filterMenu(allMenus,ids);
        }
        //4.放入session
        subject.getSession().setAttribute(MenuUtil.MENUS_IN_SESSION,allMenus);


        response.setCharacterEncoding("utf-8");
        response.setContentType("text/json;charset=utf-8");

        //登陆成功,响应JsonResult : {success:true,msg:""}
        JSONResult jsonResult = new JSONResult();
        //把对象转换成json字符串
        String jsonString = new ObjectMapper().writeValueAsString(jsonResult);

        PrintWriter writer = response.getWriter();
        writer.print(jsonString);
        writer.flush();
        writer.close();

        //返回 false,不需要再执行后面的  filter
        return false;
    }


    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response)  {

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/json;charset=utf-8");


        //登陆失败,响应JsonResult : {success:true,msg:""}
        JSONResult jsonResult = new JSONResult();

        if(e.getClass().getSimpleName().equals("UnknownAccountException")){
            jsonResult.setMsg("账户不存在的");
        }else if(e.getClass().getSimpleName().equals("IncorrectCredentialsException")) {
            jsonResult.setMsg("密码不正确");
        }else{
            jsonResult.setMsg("其他异常");
        }

        //把对象转换成json字符串
        String jsonString = null;
        try {
            jsonString = new ObjectMapper().writeValueAsString(jsonResult);
            PrintWriter writer = response.getWriter();
            writer.print(jsonString);
            writer.flush();
            writer.close();
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        return false;
    }


}
